package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;


import com.itheima.reggie.domain.Employee;

import com.itheima.reggie.service.EmployeeService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;




@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


    //登录
    @PostMapping("/login")
    public R login(HttpSession session,@RequestBody Employee employee){
        R<Employee> login = employeeService.login(employee);

        if (login.getCode()==1){
            //保存登录成功标记
            session.setAttribute("employee",login.getData().getId());
        }

        return login;
    }

    //退出
    @PostMapping("/logout")
    public R logOut(HttpSession session){
        //将session对象直接清除
        session.invalidate();
        return R.success("退出成功");
    }

    //新增员工
    @PostMapping
    public R addEmp(HttpSession session,@RequestBody Employee employee){

       /* //创建,修改人
        employee.setCreateUser((Long)session.getAttribute("employee"));
        employee.setUpdateUser((Long)session.getAttribute("employee"));*/
        //添加

        return employeeService.addEmp(employee);
    }

    //分页查询
    @GetMapping("/page")
    public R page(int page,int pageSize,String name){

        Page<Employee> p  = employeeService.findPage(page,pageSize,name);

        return R.success(p);
    }

    //id精度丢失问题: 当json数据传递给浏览器时
    // ,js会把json数据转换成js对象会进行四舍五入,导致精度丢失
    //修改员工状态
    @PutMapping
    public R updateById(@RequestBody Employee employee){
        /*//设置修改时间
        employee.setUpdateTime(LocalDateTime.now());
        //设置修改人
        employee.setUpdateUser(employee.getId());*/

        employeeService.updateById(employee);

        return R.success(null);
    }

    //数据回显
    @GetMapping("{id}")
    //因为是接收id所以参数类型是long
    public R selectById(@PathVariable Long id){

        Employee employee = employeeService.getById(id);

        return R.success(employee);
    }




    }
